package com.joint.base.service.impl;

import ch.qos.logback.core.status.StatusBase;
import com.fz.us.base.bean.BaseEnum;
import com.fz.us.base.bean.Pager;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.joint.base.activiti.JumpActivityCmd;
import com.joint.base.bean.FlowEnum;
import com.joint.base.dao.BaseEntityDao;
import com.joint.base.dao.BaseFlowDao;
import com.joint.base.entity.*;
import com.joint.base.parent.BaseFlowEntity;
import com.joint.base.service.*;
import com.joint.base.service.activiti.WorkflowService;
import com.joint.base.service.activiti.WorkflowTraceService;
import com.joint.base.util.EntityUtil;
import com.joint.base.util.StringUtils;
import com.joint.base.util.WorkflowUtils;
import org.activiti.engine.ManagementService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.*;


/**
 * Service实现类 - 
 * ============================================================================
  * 版权所有 2013 。
 * ----------------------------------------------------------------------------
 * 
 * @author 
 *
 * @version 0.1 2013-01-06
 */
@Service
public abstract class BaseFlowServiceImpl<T extends BaseFlowEntity,PK extends String> extends BaseEntityServiceImpl<T, PK> implements BaseFlowService<T,PK> {
    @Resource
    protected WorkflowTraceService workflowTraceService;
    @Resource
    protected WorkflowService workflowService;
    @Resource
    protected UsersService usersService;
    @Resource
    protected ProcessConfigService processConfigService;
    @Resource
    protected RuntimeService runtimeService;
    @Resource
    protected ManagementService managementService;
    @Resource
    protected BusinessConfigService businessConfigService;
    @Resource
    protected TaskService taskService;
    @Resource
    protected CommentTypeService commentTypeService;
    @Resource
    protected TaskRecordService taskRecordService;
    //add by zhucx
    @Resource
    protected TaskEntityService taskEntityService;
    //add by zhucx
    @Resource
    protected TaskFlowService taskFlowService;
    //add by zhucx
    @Resource
    protected ProcessBriefService processBriefService;
    //add by zhucx
    @Resource
    protected StepBriefService stepBriefService;
    //add by zhucx
    @Resource
    protected CommonConfigService commonConfigService;
    //add by zhucx
    @Resource
    protected StepConService stepConService;
    //add by zhucx
    @Resource
    protected JointlySignService jointlySignService;
    //add by zhucx
    @Resource
    protected DutyService dutyService;

    public abstract BaseFlowDao<T,PK> getBaseFlowDao();

    @Override
    public BaseEntityDao<T, PK> getBaseEntityDao() {
        return getBaseFlowDao();
    }


    @Override
    //add by zhucx
    public PK save(T entity, String entityName) {
        Users users = usersService.getLoginInfo();
        entity.setProcessState(FlowEnum.ProcessState.Draft);
        PK pk =  save(entity);
        TaskEntity taskEntity = taskEntityService.get(pk);
        if(taskEntity == null){
            taskEntity = new TaskEntity();
            taskEntity.setCreater(users);
            taskEntity.setKeyId(pk);
            taskEntity.setStepNo(1);
            taskEntity.setEntityName(entityName);
            taskEntity.setProcessState(FlowEnum.ProcessState.Draft);
            taskEntityService.save(taskEntity);
        }
        return pk;
    }

    @Override
    public PK save(T entity,String process,Map<String,Object> various) {
        entity.setProcessState(FlowEnum.ProcessState.Draft);
        BusinessConfig businessConfig = businessConfigService.getByBusinessKey(process);
        entity.setVersion(businessConfig.getVersion());
        PK pk =  save(entity);
        //发起流程
        ProcessInstance proIntance = workflowTraceService.createFlow(process, entity.getId(), various);
        return pk;
    }

    @Override
    //add by zhucx
    public PK commit(T entity, String entityName, Duty duty) {
        Users users = usersService.getLoginInfo();
        PK pk = save(entity);
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(pk);
        //已办标志
        int type = 1;
        //下一步步骤简要表对象
        StepBrief  stepBrief = null;
        if(taskEntity == null){
            taskEntity = new TaskEntity();
            taskEntity.setCreater(users);
            taskEntity.setKeyId(pk);
            ProcessBrief processBrief = processBriefService.getInfoByTableKey(entityName);
            StepBrief firstStepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
            if(firstStepBrief.getRouteType() != 2){ //一般路由
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, firstStepBrief.getNextStepNo());
            }else{ //条件路由
                Map<String, Object> parmas = new HashMap<String, Object>();
                parmas.put("stepBrief", firstStepBrief);
                parmas.put("state", BaseEnum.StateEnum.Enable);
                List<StepCon> stepConList = stepConService.getList(parmas);
                for(StepCon stepCon:stepConList){
                    if(calStepCon(stepCon.getFormulaField(),stepCon.getFormulaFlag(),stepCon.getFormulaVal(),pk,entityName) == true){
                        stepBrief = stepBriefService.getInfoByStepNo(processBrief, stepCon.getStepNo());
                        break;
                    }
                }
            }
            Set<Users> editors = new HashSet<Users>();
            Set<Users> readers = new HashSet<Users>();
            if(stepBrief == null){//直接归档
                type = 2;
                taskEntity.setStepNo(1);
                taskEntity.setProcessState(FlowEnum.ProcessState.Finished);
                entity.setProcessState(FlowEnum.ProcessState.Finished);
                List<Duty> docDutyList = Lists.newArrayList();
                if(processBrief.getDocConfig() != null){
                    docDutyList = commonConfigService.findDutyByConfig(pk,entityName, processBrief.getDocConfig().getId());
                }
                List<Duty> editDutyList = Lists.newArrayList();
                if(processBrief.getEditConfig() != null){
                    editDutyList = commonConfigService.findDutyByConfig(pk,entityName, processBrief.getEditConfig().getId());
                }
                List<Duty> readDutyList = Lists.newArrayList();
                if(processBrief.getReadConfig() != null){
                    readDutyList = commonConfigService.findDutyByConfig(pk, entityName, processBrief.getReadConfig().getId());
                }
                docDutyList.addAll(editDutyList);
                docDutyList.addAll(readDutyList);
                for(Duty readDuty: docDutyList){
                    if(readDuty.getUsers() != null){
                        readers.add(readDuty.getUsers());
                    }
                }
                for(Duty editDuty: editDutyList){
                    if(editDuty.getUsers() != null){
                        editors.add(editDuty.getUsers());
                    }
                }
            }else{//流转
                taskEntity.setStepNo(stepBrief.getStepNo());
                taskEntity.setProcessState(FlowEnum.ProcessState.Running);
                entity.setProcessState(FlowEnum.ProcessState.Running);
                List<Duty> editDutyList = Lists.newArrayList();
                if(stepBrief.getCommonConfig() != null){
                    editDutyList = commonConfigService.findDutyByConfig(pk, entityName, stepBrief.getCommonConfig().getId());
                }
                List<Duty> docDutyList = Lists.newArrayList();
                if(processBrief.getDocConfig() != null){
                    docDutyList = commonConfigService.findDutyByConfig(pk, entityName, processBrief.getDocConfig().getId());
                }
                List<Users> specialUsersList = stepBriefService.findSpecailByUser(stepBrief, duty);
                for(Duty editDuty: editDutyList){
                   if(editDuty.getUsers() != null){
                       editors.add(editDuty.getUsers());
                   }
                }
                editors.addAll(specialUsersList);
                docDutyList.addAll(editDutyList);
                for(Duty readDuty: docDutyList){
                    if(readDuty.getUsers() != null){
                        readers.add(readDuty.getUsers());
                    }
                }
                readers.addAll(specialUsersList);
            }
            readers.add(users);
            Set<Users> prevUsers = Sets.newHashSet();
            prevUsers.add(users);
            taskEntity.setPrevUsers(prevUsers);
            taskEntity.setEntityName(entityName);
            taskEntity.setReaders(readers);
            taskEntity.setEditors(editors);
            taskEntityService.save(taskEntity);
            update(entity);
        }

        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUsers(users);
        taskFlow.setDuty(duty);
        taskFlow.setType(FlowEnum.TaskFlowType.create);
        taskFlow.setStepBrief(stepBrief);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
        return pk;
    }

    @Override
    public PK commit(T entity, String process, Map<String, Object> var1, Map<String, Object> var2,String curDutyId) {


        entity.setProcessState(FlowEnum.ProcessState.Running);
        PK pk =  save(entity);
        //发起流程
        workflowTraceService.createFlow(process, entity.getId(), var1);

        Task task = workflowService.getCurrentTask(entity.getId(), usersService.getLoginInfo());
      //  LogUtil.info("task:"+task);
        workflowTraceService.processAppprove(task, var2, curDutyId);
        /*
       if(workflowService.getCurrentTask(entity.getId(), usersService.getLoginInfo())==null){
           entity.setProcessState(FlowEnum.ProcessState.Finished);
            update(entity);
       }*/
        Users users = usersService.getLoginInfo();
        List<TaskRecord> taskRecordList =taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(1);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
        return pk;
    }

    @Override
    public PK commit(T entity, FlowEnum.ProcessState processState, String process, Map<String, Object> var1, Map<String, Object> var2,String curDutyId) {


        entity.setProcessState(processState);
        PK pk =  save(entity);
        //发起流程
        workflowTraceService.createFlow(process,entity.getId(),var1);

        Task task = workflowService.getCurrentTask(entity.getId(), usersService.getLoginInfo());
        //  LogUtil.info("task:"+task);
        workflowTraceService.processAppprove(task,var2,curDutyId);
        /*
       if(workflowService.getCurrentTask(entity.getId(), usersService.getLoginInfo())==null){
           entity.setProcessState(FlowEnum.ProcessState.Finished);
            update(entity);
       }*/
        Users users = usersService.getLoginInfo();
        List<TaskRecord> taskRecordList =taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            if(StringUtils.equals(processState.name(), "Finished")){
                taskRecord.setType(2);
            }else{
                taskRecord.setType(1);
            }
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
        return pk;
    }
    /**
     * 废弃
     * @param entity
     * @param process
     * @param var1
     * @param var2
     * @param taskDefKey
     * @param varAssign
     * @param curDutyId
     * @return
     */
    @Override
    public PK commit(T entity, String process, Map<String, Object> var1, Map<String, Object> var2, String taskDefKey ,String varAssign, String curDutyId) {
        entity.setProcessState(FlowEnum.ProcessState.Running);
        PK pk =  save(entity);
        //发起流程
        workflowTraceService.createFlow(process,entity.getId(),var1);

        Task task = workflowService.getCurrentTask(entity.getId(),usersService.getLoginInfo());
        ProcessInstance processInstance = workflowService.getProIntanceByTask(task);
        approve(entity, null, var2,taskDefKey, varAssign, curDutyId);

        return pk;
    }
    //add by zhucx
    //todo
    @Override
    public void approve(T entity, Duty duty, String comment) {
        Users users = usersService.getLoginInfo();
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        //流程简要
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(taskEntity.getEntityName());
        //当前步骤
        StepBrief nowStepBrief = stepBriefService.getInfoByStepNo(processBrief, taskEntity.getStepNo());
        //下一步骤
        StepBrief stepBrief = null;
        //会签删除当前用户的人员
        Set<Users> delUsersSet = Sets.newHashSet();
        //不是会签
        if(nowStepBrief.isJointlySing() == false){
            if(nowStepBrief.getRouteType() != 2){ //一般路由
                stepBrief = stepBriefService.getInfoByStepNo(processBrief, nowStepBrief.getNextStepNo());
            }else{ //条件路由
                Map<String, Object> parmas = new HashMap<String, Object>();
                parmas.put("stepBrief", nowStepBrief);
                parmas.put("state", BaseEnum.StateEnum.Enable);
                List<StepCon> stepConList = stepConService.getList(parmas);
                for(StepCon stepCon:stepConList){
                    if(calStepCon(stepCon.getFormulaField(),stepCon.getFormulaFlag(),stepCon.getFormulaVal(),entity.getId(),taskEntity.getEntityName()) == true){
                        stepBrief = stepBriefService.getInfoByStepNo(processBrief, stepCon.getStepNo());
                        break;
                    }
                }
            }
        }else{ //会签
            Map<String, Object> params = new HashMap<>();
            params.put("taskEntity", taskEntity);
            params.put("stepBrief", nowStepBrief);
            params.put("state", BaseEnum.StateEnum.Enable);
            Set<JointlySign> jointlySignSet = Sets.newHashSet();
            jointlySignSet.addAll(jointlySignService.getList(params)) ;
            if(jointlySignSet.size() == 0){ //没有会签信息数据，说明是第一次生成
                List<Duty> editDutyList = Lists.newArrayList();
                Set<Users> editors = new HashSet<>();
                if(nowStepBrief.getCommonConfig() != null){
                    editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), nowStepBrief.getCommonConfig().getId());
                }
                List<Users> specialUsersList = stepBriefService.findSpecailByUser(nowStepBrief, duty);
                for(Duty editDuty: editDutyList){
                    if(editDuty.getUsers() != null){
                        editors.add(editDuty.getUsers());
                    }
                }
                editors.addAll(specialUsersList);
                for(Users users1:editors){
                    JointlySign jointlySign = new JointlySign();
                    jointlySign.setTaskEntity(taskEntity);
                    jointlySign.setStepBrief(nowStepBrief);
                    jointlySign.setUsers(users1);
                    if(users == users1){
                        jointlySign.setFinish(true);
                    }else{
                        jointlySign.setFinish(false);
                    }
                    jointlySignService.save(jointlySign);
                }
                delUsersSet.add(users);
                stepBrief = nowStepBrief;
            }else{//有会签数据，要更新完成状态
                for(JointlySign jointlySign:jointlySignSet){
                    if(jointlySign.getUsers() == users){
                        jointlySign.setFinish(true);
                        jointlySignService.update(jointlySign);
                        break;
                    }
                }
                //查找做完的会签
                Map<String, Object> params2 = new HashMap<>();
                params2.put("taskEntity", taskEntity);
                params2.put("stepBrief", nowStepBrief);
                params2.put("state", BaseEnum.StateEnum.Enable);
                params2.put("finish", true);
                Set<JointlySign>  jointlySignFinishSet = Sets.newHashSet();
                jointlySignFinishSet.addAll(jointlySignService.getList(params2)) ;
                for(JointlySign jointlySign:jointlySignFinishSet){
                    delUsersSet.add(jointlySign.getUsers());
                }
                //数量一样，表示都会签完成，可以走下一步，否则还是当前步骤
                if(jointlySignFinishSet.size() == jointlySignSet.size()){
                    if(nowStepBrief.getRouteType() != 2) { //一般路由
                        stepBrief = stepBriefService.getInfoByStepNo(processBrief, nowStepBrief.getNextStepNo());
                    }else{ //条件路由
                        Map<String, Object> parmas = new HashMap<String, Object>();
                        parmas.put("stepBrief", nowStepBrief);
                        parmas.put("state", BaseEnum.StateEnum.Enable);
                        List<StepCon> stepConList = stepConService.getList(parmas);
                        for(StepCon stepCon:stepConList){
                            if(calStepCon(stepCon.getFormulaField(),stepCon.getFormulaFlag(),stepCon.getFormulaVal(),entity.getId(),taskEntity.getEntityName()) == true){
                                stepBrief = stepBriefService.getInfoByStepNo(processBrief, stepCon.getStepNo());
                                break;
                            }
                        }
                    }
                }else{
                    stepBrief = nowStepBrief;
                }
            }
        }


        Set<Users> editors = new HashSet<Users>();
        Set<Users> readers = new HashSet<Users>();
        //已办标志
        int type = 1;
        if(stepBrief == null){//直接归档
            type = 2;
            taskEntity.setStepNo(nowStepBrief.getNextStepNo());
            taskEntity.setProcessState(FlowEnum.ProcessState.Finished);
            entity.setProcessState(FlowEnum.ProcessState.Finished);
            List<Duty> docDutyList = Lists.newArrayList();
            if(processBrief.getDocConfig() != null){
                docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
            }
            List<Duty> editDutyList = Lists.newArrayList();
            if(processBrief.getEditConfig() != null){
                editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getEditConfig().getId());
            }
            List<Duty> readDutyList = Lists.newArrayList();
            if(processBrief.getReadConfig() != null){
                readDutyList = commonConfigService.findDutyByConfig(entity.getId(), taskEntity.getEntityName(), processBrief.getReadConfig().getId());
            }
            docDutyList.addAll(editDutyList);
            docDutyList.addAll(readDutyList);
            for(Duty readDuty: docDutyList){
                if(readDuty.getUsers() != null){
                    readers.add(usersService.get(readDuty.getUsers().getId()));
                }
            }
            for(Duty editDuty: editDutyList){
                if(editDuty.getUsers() != null){
                    editors.add(usersService.get(editDuty.getUsers().getId()));
                }
            }
        }else{//流转


            /*
            List<TaskFlow> taskFlowList = taskFlowService.getTaskFlowByCreatetime();
            if(taskFlowList.size()>0){
                TaskFlow taskFlow = taskFlowList.get(taskFlowList.size()-1);
                prevUsers.add(taskFlow.getUsers());
            }*/

            taskEntity.setStepNo(stepBrief.getStepNo());
            taskEntity.setProcessState(FlowEnum.ProcessState.Running);
            entity.setProcessState(FlowEnum.ProcessState.Running);
            List<Duty> editDutyList = Lists.newArrayList();
            if(stepBrief.getCommonConfig() != null){
                editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), stepBrief.getCommonConfig().getId());
            }
            List<Duty> docDutyList = Lists.newArrayList();
            if(processBrief.getDocConfig() != null){
                docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
            }
            List<Users> specialUsersList = stepBriefService.findSpecailByUser(stepBrief, duty);
            for(Duty editDuty: editDutyList){
                if(editDuty.getUsers() != null){
                    editors.add(editDuty.getUsers());
                }
            }
            editors.addAll(specialUsersList);
            //会签时，要删除会签过的人
            if(stepBrief == nowStepBrief){
                editors.removeAll(delUsersSet);
            }
            docDutyList.addAll(editDutyList);
            for(Duty readDuty: docDutyList){
                if(readDuty.getUsers() != null){
                    readers.add(readDuty.getUsers());
                }
            }
            readers.addAll(specialUsersList);
        }

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnum.StateEnum.Enable);
        params.put("taskEntity", taskEntity);
        List<TaskFlow> taskFlowList1 = taskFlowService.getList(params);
        for(TaskFlow taskFlow:taskFlowList1){
            readers.add(taskFlow.getUsers());
        }
        readers.add(users);
        Set<Users> prevUsers = Sets.newHashSet();
        prevUsers.add(users);
        taskEntity.setPrevUsers(prevUsers);
        taskEntity.setReaders(readers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUsers(users);
        taskFlow.setDuty(duty);
        taskFlow.setComment(comment);
        taskFlow.setType(FlowEnum.TaskFlowType.approve);
        taskFlow.setStepBrief(stepBrief);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
        if(type == 2){
            for(TaskRecord taskRecord:taskRecords){
                taskRecord.setType(2);
                taskRecordService.update(taskRecord);
            }
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }

    }

    /**
     * @update 2017-02-14
     * @author zhucx
     * 增加已办数据
     */
    @Override
    public void approve(T entity, FlowEnum.ProcessState processState,Map<String, Object> var,String curDutyId,String comment) {

        if(processState != null){
            entity.setProcessState(processState);
            update(entity);
        }
        Task task = workflowService.getCurrentTask(entity.getId(),usersService.getLoginInfo());
        //增加流程已经类型数据
        if(comment != null) {
            String commentId = taskService.addComment(task.getId(), task.getProcessInstanceId(), comment).getId();
            CommentType commentType = new CommentType();
            commentType.setCommentId(commentId);
            commentType.setType("提交审批");
            commentTypeService.save(commentType);
        }
        try {
            workflowTraceService.processAppprove(task,var,curDutyId);
        } catch (Exception e) {
            throw e;
        }
        Users users = usersService.getLoginInfo();
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
        if(StringUtils.equals(processState.name(),"Finished")){
            for(TaskRecord taskRecord:taskRecords){
                taskRecord.setType(2);
                taskRecordService.update(taskRecord);
            }
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            if(StringUtils.equals(processState.name(), "Finished")){
                taskRecord.setType(2);
            }else{
                taskRecord.setType(1);
            }
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
    }

    /**
     * 废弃
     * @param entity
     * @param processState
     * @param var
     * @param taskDefKey
     * @param varAssign
     * @param curDutyId
     */
    @Override
    public void approve(T entity, FlowEnum.ProcessState processState, Map<String, Object> var, String taskDefKey,String varAssign, String curDutyId) {
        if(processState != null){
            entity.setProcessState(processState);
            update(entity);
        }
        Task task = workflowService.getCurrentTask(entity.getId(),usersService.getLoginInfo());

        workflowTraceService.processAppprove(task,var,curDutyId);


    }



    @Override
    public void reject(T entity, String taskDefKey, int numStatus,String comment,String curDutyId) {

        entity.setProcessState(FlowEnum.ProcessState.Backed);
        super.update(entity);
        Users loginer = usersService.getLoginInfo();
        Task task = workflowService.getCurrentTask(entity.getId(), loginer);

        //增加流程已经类型数据
        if(comment != null) {
            String commentId = taskService.addComment(task.getId(), task.getProcessInstanceId(), comment).getId();
            CommentType commentType = new CommentType();
            commentType.setCommentId(commentId);
            commentType.setType("退回流程");
            commentTypeService.save(commentType);
        }
        taskService.claim(task.getId(), loginer.getId());
        taskService.setVariableLocal(task.getId(), "curDutyId",curDutyId);
        ProcessInstance proInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(entity.getId()).singleResult();
        Command<Object> command= new JumpActivityCmd(proInstance.getId(),taskDefKey,numStatus);
        managementService.executeCommand(command);

        Users users = usersService.getLoginInfo();
        List<TaskRecord> taskRecordList =taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(1);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
    }

    @Override
    public void back(T entity, Duty duty, String comment) {
        Users users = usersService.getLoginInfo();
        //任务实体
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(taskEntity.getEntityName());
        StepBrief nowStepBrief = stepBriefService.getInfoByStepNo(processBrief, taskEntity.getStepNo());
        int backStepNo = nowStepBrief.getBackStepNo() == 0?1:nowStepBrief.getBackStepNo();
        StepBrief  stepBrief = stepBriefService.getInfoByStepNo(processBrief, backStepNo);
        Set<Users> editors = new HashSet<Users>();
        Set<Users> readers = new HashSet<Users>();
        //已办标志
        int type = 1;
        if(stepBrief == null){//到第一步
           stepBrief = stepBriefService.getInfoByStepNo(processBrief, 1);
        }

        /*
        List<TaskFlow> taskFlowList = taskFlowService.getTaskFlowByCreatetime();
        if(taskFlowList.size()>0){
            TaskFlow taskFlow = taskFlowList.get(taskFlowList.size()-1);
            prevUsers.add(taskFlow.getUsers());
        }*/

        taskEntity.setStepNo(stepBrief.getStepNo());
        taskEntity.setProcessState(FlowEnum.ProcessState.Backed);
        entity.setProcessState(FlowEnum.ProcessState.Backed);
        List<Duty> editDutyList = Lists.newArrayList();
        if(stepBrief.getStepNo() == 1){
            editDutyList.addAll(dutyService.getDutys(entity.getCreater()));
        }else{
            if(stepBrief.getCommonConfig() != null){
                editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), stepBrief.getCommonConfig().getId());
            }
        }

        List<Duty> docDutyList = Lists.newArrayList();
        if(processBrief.getDocConfig() != null){
            docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
        }
        for(Duty editDuty: editDutyList){
            if(editDuty.getUsers() != null){
                editors.add(usersService.get(editDuty.getUsers().getId()));
            }
        }
        List<Users> specialUsersList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(stepBrief.getSpecialType())){
            List<TaskFlow> taskFlowList = taskFlowService.getInfoByTaskStepBrief(taskEntity, stepBrief);
            for(TaskFlow taskFlow: taskFlowList){
                specialUsersList.addAll(stepBriefService.findSpecailByUser(stepBrief, taskFlow.getDuty()));
            }
        }
        readers.addAll(specialUsersList);
        if(stepBrief.getStepNo() != 1){
            editors.addAll(specialUsersList);
        }
        docDutyList.addAll(editDutyList);
        for(Duty readDuty: docDutyList){
            if(readDuty.getUsers() != null){
                readers.add(usersService.get(readDuty.getUsers().getId()));
            }
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnum.StateEnum.Enable);
        params.put("taskEntity", taskEntity);
        List<TaskFlow> taskFlowList1 = taskFlowService.getList(params);
        for(TaskFlow taskFlow:taskFlowList1){
            readers.add(taskFlow.getUsers());
        }
        readers.add(users);
        Set<Users> prevUsers = Sets.newHashSet();
        prevUsers.add(users);
        taskEntity.setPrevUsers(prevUsers);
        taskEntity.setReaders(readers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUsers(users);
        taskFlow.setDuty(duty);
        taskFlow.setComment(comment);
        taskFlow.setType(FlowEnum.TaskFlowType.back);
        taskFlow.setStepBrief(stepBrief);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
        //删除所有对应会签信息，重新开始会签
        Map<String, Object> params2 = new HashMap<>();
        params2.put("taskEntity", taskEntity);
        params2.put("state", BaseEnum.StateEnum.Enable);
        List<JointlySign> jointlySignList = jointlySignService.getList(params2);
        for(JointlySign jointlySign:jointlySignList){
            jointlySign.setState(BaseEnum.StateEnum.History);
            jointlySignService.update(jointlySign);
        }
    }

    @Override
    public void destroy(T entity) {
        entity.setProcessState(FlowEnum.ProcessState.Destroy);
        entity.setState(BaseEnum.StateEnum.Disenable);
        if (runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(entity.getId()).active().list().size() > 0) {
            ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(entity.getId()).active().singleResult();
            runtimeService.suspendProcessInstanceById(processInstance.getId());
        }
        super.update(entity);
    }

    @Override
    public void deny(T entity, String taskDefKey,String comment,String curDutyId) {

        entity.setProcessState(FlowEnum.ProcessState.Deny);
        super.update(entity);
        Users loginer = usersService.getLoginInfo();
        Task task = workflowService.getCurrentTask(entity.getId(), loginer);
        //增加流程已经类型数据
        if(comment != null) {
            String commentId = taskService.addComment(task.getId(), task.getProcessInstanceId(), comment).getId();
            CommentType commentType = new CommentType();
            commentType.setCommentId(commentId);
            commentType.setType("否决流程");
            commentTypeService.save(commentType);
        }
        taskService.claim(task.getId(), loginer.getId());
        taskService.setVariableLocal(task.getId(), "curDutyId", curDutyId);
        ProcessInstance proInstance = runtimeService.createProcessInstanceQuery().processInstanceBusinessKey(entity.getId()).singleResult();
        Command<Object> command= new JumpActivityCmd(proInstance.getId(),taskDefKey,"否决", -1);
        managementService.executeCommand(command);

        Users users = usersService.getLoginInfo();
        List<TaskRecord> taskRecordList =taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());

        for(TaskRecord taskRecord:taskRecords){
            taskRecord.setType(2);
            taskRecordService.update(taskRecord);
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(2);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }

    }

    @Override
    public void deny(T entity, Duty duty, String comment) {
        Users users = usersService.getLoginInfo();
        TaskEntity taskEntity = taskEntityService.getInfoByKeyId(entity.getId());
        ProcessBrief processBrief = processBriefService.getInfoByTableKey(taskEntity.getEntityName());
        Set<Users> editors = new HashSet<Users>();
        Set<Users> readers = new HashSet<Users>();
        //已办标志
        int type = 2;
        taskEntity.setProcessState(FlowEnum.ProcessState.Deny);
        entity.setProcessState(FlowEnum.ProcessState.Deny);
        List<Duty> docDutyList = Lists.newArrayList();
        if(processBrief.getDocConfig() != null){
            docDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getDocConfig().getId());
        }
        List<Duty> editDutyList = Lists.newArrayList();
        if(processBrief.getEditConfig() != null){
            editDutyList = commonConfigService.findDutyByConfig(entity.getId(),taskEntity.getEntityName(), processBrief.getEditConfig().getId());
        }
        List<Duty> readDutyList = Lists.newArrayList();
        if(processBrief.getReadConfig() != null){
            readDutyList = commonConfigService.findDutyByConfig(entity.getId(), taskEntity.getEntityName(), processBrief.getReadConfig().getId());
        }
        docDutyList.addAll(editDutyList);
        docDutyList.addAll(readDutyList);
        for(Duty readDuty: docDutyList){
            if(readDuty.getUsers() != null){
                readers.add(usersService.get(readDuty.getUsers().getId()));
            }
        }
        for(Duty editDuty: editDutyList){
            if(editDuty.getUsers() != null){
                editors.add(usersService.get(editDuty.getUsers().getId()));
            }
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("state", BaseEnum.StateEnum.Enable);
        params.put("taskEntity", taskEntity);
        List<TaskFlow> taskFlowList1 = taskFlowService.getList(params);
        for(TaskFlow taskFlow:taskFlowList1){
            readers.add(taskFlow.getUsers());
        }
        readers.add(users);
        Set<Users> prevUsers = Sets.newHashSet();
        prevUsers.add(users);
        taskEntity.setPrevUsers(prevUsers);
        taskEntity.setReaders(readers);
        taskEntity.setEditors(editors);
        taskEntityService.update(taskEntity);
        update(entity);
        //任务流程信息
        TaskFlow taskFlow = new TaskFlow();
        taskFlow.setTaskEntity(taskEntity);
        taskFlow.setUsers(users);
        taskFlow.setDuty(duty);
        taskFlow.setComment(comment);
        taskFlow.setType(FlowEnum.TaskFlowType.deny);
        taskFlowService.save(taskFlow);
        //已办事宜
        List<TaskRecord> taskRecordList = taskRecordService.getDataByUserKeyId(entity.getId(), users.getId());
        List<TaskRecord> taskRecords = taskRecordService.getDataByKeyId(entity.getId());
        for(TaskRecord taskRecord:taskRecords){
            taskRecord.setType(2);
            taskRecordService.update(taskRecord);
        }
        if(taskRecordList.size() == 0){
            TaskRecord taskRecord = new TaskRecord();
            taskRecord.setUsers(users);
            taskRecord.setKeyId(entity.getId());
            taskRecord.setType(type);
            taskRecord.setBussinessKey(entity.getClass().getName());
            taskRecord.setModule(WorkflowUtils.getModularName(entity));
            taskRecordService.save(taskRecord);
        }
    }

    @Override
    public Pager findByPagerAndDraft(Users users, Pager pager, Map<String,Object> rmap) {
        return getBaseFlowDao().findByPagerAndDraft(users,pager,rmap);
    }

    @Override
    public Pager findByPagerAndLimit(String entityName, FlowEnum.ProcessState[] processState, Pager pager, Map<String,Object> rmap ) {
        return getBaseFlowDao().findByPagerAndLimit(entityName, processState, pager, rmap);
    }

    @Override
    public Pager findByPagerAndLimit(boolean type,String procssKey,Pager pager,Map<String,Object> rmap) {
        return getBaseFlowDao().findByPagerAndLimit(type,procssKey,pager, rmap);
    }

    @Override
    public Pager findByPagerAndFinish(String procssKey,Pager pager, Map<String,Object> rmap) {
       // BusinessConfig bcfg = businessConfigService.getByBusinessKey(procssKey);
        return getBaseFlowDao().findByPagerAndFinish(procssKey,pager, rmap);
    }

    @Override
    public Pager findByPagerAndBack(Pager pager, Map<String,Object> rmap) {
        return getBaseFlowDao().findByPagerAndBack(pager, rmap);
    }

    @Override
    public Pager findByPagerAndProcessState(Pager pager, Users users,String businessKey,FlowEnum.ProcessState processState,Map<String, Object> rmap){
        return getBaseFlowDao().findByPagerAndProcessState(pager,users,businessKey,processState,rmap);
    }

    @Override
    public boolean calStepCon(String formulaField, String formulaFlag, String formulaVal, String keyId, String entityName) {
        ScriptEngineManager manager = new ScriptEngineManager();
        ScriptEngine se = manager.getEngineByName("js");
        String className = entityName.substring(entityName.lastIndexOf(".") + 1);
        Object object = this.getObjectEntity(keyId, className);
        boolean result = false;
        if(object != null) {
            Object obj = EntityUtil.getFieldValueByName(formulaField, object);
            String formula = "";
            String str = "";
            if(StringUtils.equals("==", formulaFlag) || StringUtils.equals("!=", formulaFlag)){
                formula = formulaField + formulaFlag + "\""+ formulaVal + "\"" ;
                str = "var "+formulaField+"=\"" +obj+ "\";"+formula;
            }else{
                formula = formulaField + formulaFlag + formulaVal ;
                str = "var "+formulaField+"="+obj+ ";"+formula;
            }
            try {
                result = (boolean) se.eval(str);
            } catch (ScriptException e) {
                e.printStackTrace();
            }
        }
        return  result;
    }


}